package com.lyh.hkcloud.module.m1300090;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lyh.hkcloud.R;
import com.lyh.hkcloud.base.BaseActivity;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.common.ActivityUtil;
import com.lyh.hkcloud.module.m1300090.service.Service;
import com.lyh.hkcloud.module.m1300090.adapter.RecyclerViewAdapter;
import com.lyh.hkcloud.util.base.JsonUtil;
import com.lyh.hkcloud.util.base.SaveData;
import com.lyh.hkcloud.util.base.StringUtils;
import com.lyh.hkcloud.util.base.ToastUtils;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * @author: wwl
 * @program: hkCloud
 * @description:
 * @company—date: 利元数据 2024-05-03 16:59
 **/
public class IndexActivity extends BaseActivity implements View.OnClickListener{

    private ImageView goBack;
    private Button btReceiver;
    //private Button btSave;
    private Button btInventoryCompleted;
    private LinearLayout llButton;
    private EditText etAssets;
    private Service service;
    private TextView tvInventoryNo;
    private String inventoryPlanId;
    private String scanResultCode;
    private TextView tvInventoryTime;
    private TextView tvInventoryUserName;

    private RecyclerView recyclerView;
    private List<Map<String, Object>> dataMap = new ArrayList<>();
    private RecyclerViewAdapter recyclerViewAdapter;
    private Integer receiverFocusEvent = 0;
    List<String> assetIdList = new ArrayList<>();

    private Integer initialAssetsNum = 0;

    /**
     * 上一个页面传过来的 盘点id和盘点状态
     */
    private JSONObject data;

    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected int getSubmitResId() {
        return R.id.bt_receiver;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_1300090;
    }

    @Override
    protected void onBeginInit() {
        service = new Service(IndexActivity.this);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView() {
        goBack = findViewById(R.id.go_back);
        recyclerView = findViewById(R.id.recyclerView);
        btReceiver = findViewById(R.id.bt_receiver);
        //btSave = findViewById(R.id.bt_save);
        llButton = findViewById(R.id.ll_button);
        //btInventoryCompleted = findViewById(R.id.bt_inventory_completed);
        etAssets = findViewById(R.id.et_assets);
        tvInventoryNo = findViewById(R.id.tv_inventoryNo);
        tvInventoryTime = findViewById(R.id.tv_inventoryTime);
        tvInventoryUserName = findViewById(R.id.tv_inventoryUserName);
        //获得焦点，并关闭软盘
        etAssets.setShowSoftInputOnFocus(false);
        goBack.setOnClickListener(this);
        getSupportActionBar().hide();

        //获取盘点列表页面的参数
        try {
            data = new JSONObject(getIntent().getStringExtra(BusinessConstants.DATA));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        recyclerViewAdapter = new RecyclerViewAdapter(dataMap);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        recyclerView.setAdapter(recyclerViewAdapter);
        recyclerViewAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {

            @Override
            public void click(RecyclerViewAdapter.VH vh,View view) {
                //Toast.makeText(IndexActivity.this, vh.cardNumber.getText(),Toast.LENGTH_SHORT).show();
                int id = view.getId();
                //单号
                String inventoryNo = tvInventoryNo.getText().toString();
                //实物码
                String cardNumber = vh.cardNumber.getText().toString();

                if (R.id.bt_update_used == id) {
                    //单号
                    //打开修改使用人资产信息页面
                    Intent intent = new Intent(view.getContext(), UpdateUsedActivity.class);
                    intent.putExtra("cardNumber", cardNumber);
                    intent.putExtra("inventoryNo", inventoryNo);
                    startActivityForResult(intent, 1);
                }else if(R.id.bt_update_location == id) {
                    //打开修改位置资产信息页面
                    Intent intent = new Intent(view.getContext(), UpdateLocationActivity.class);
                    intent.putExtra("cardNumber", cardNumber);
                    intent.putExtra("inventoryNo", inventoryNo);
                    startActivityForResult(intent, 1);
                }else if (R.id.bt_update_exceptionMemo == id) {
                    String exceptionMemo = vh.exceptionMemo.getText().toString();
                    //打开修改位置资产信息页面
                    Intent intent = new Intent(view.getContext(), UpdateExceptionMemo.class);
                    intent.putExtra("cardNumber", cardNumber);
                    intent.putExtra("inventoryNo", inventoryNo);
                    intent.putExtra(BusinessConstants.EXCEPTION_MEMO, exceptionMemo);
                    startActivityForResult(intent, 1);
                }
            }
        });

        try {
            tvInventoryNo.setText(data.getString(BusinessConstants.INVENTORY_NO));
            inventoryPlanId = data.getString(BusinessConstants.ID);
            scanResultCode = data.getString(BusinessConstants.SCAN_RESULT_CODE);
            tvInventoryTime.setText(data.getString(BusinessConstants.INVENTORY_TIME));
            tvInventoryUserName.setText(data.getString(BusinessConstants.INVENTORY_USER_NAME));
            //通过盘点计划id查询已盘点资产信息
            queryCountAssets();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        registerReceiver(receiver, Filter());
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterReceiver(receiver);
    }

    private static IntentFilter Filter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BusinessConstants.ACTION);
        return intentFilter;
    }

    @Override
    protected void initEvent() {
        etAssets.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (BusinessConstants.SCAN_WHEN_ASSETS.equals(String.valueOf(etAssets.getText()))) {
                        etAssets.setText("");
                    }
                    receiverFocusEvent = 1;
                } else {
                    if (etAssets.getText() == null || "".equals(String.valueOf(etAssets.getText()))) {
                        etAssets.setText(BusinessConstants.SCAN_WHEN_ASSETS);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });

        //回车事件，查询资产
        etAssets.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //查询资产
                JSONObject jsonObject = new JSONObject();
                try {
                    String msg = etAssets.getText().toString().replace(BusinessConstants.SCAN_WHEN_ASSETS, "");
                    if (assetIdList.indexOf(msg) != -1) {
                        Toast.makeText(IndexActivity.this, "请不要重复扫描", Toast.LENGTH_SHORT).show();
                    } else if (StringUtils.isNotEmpty(msg)) {
                        jsonObject.put("psncode", msg);
                        jsonObject.put("facardcode", msg);
                        queryAssets(jsonObject);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                etAssets.setText("");
                return true;
            }
        });
    }

    @Override
    protected void onSubmit() {

        //校验 是否扫描了资产
        if (dataMap.size() > initialAssetsNum) {
            ToastUtils.makeText(this, "请先暂存资产，然后执行盘点过账", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        btReceiver.setEnabled(false);

        //先暂存资产
        //SaveInventoryAssets();

//        this.inventoryVariance();
        Map<String, Object> inventoryAssetsMap = new HashMap<>();

        inventoryAssetsMap.put("dataIds", Arrays.asList(data.optString(BusinessConstants.ID)));
        inventoryAssetsMap.put("userid", SaveData.getString(this, "userid"));
        inventoryAssetsMap.put("username", SaveData.getString(this, "userName"));
        try {
            inventoryAssetsMap.put(BusinessConstants.INVENTORY_ID, data.getString(BusinessConstants.INVENTORY_ID));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        service.post(JsonUtil.toJSONObject(inventoryAssetsMap), HttpUrlComstants.INVENTORY_POSTING, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
            }
        });
        try {
            //加休眠，不然报错
            Thread.sleep(1000);
        } catch (Exception e) {
            Log.e("error", e.toString());
        }
        //返回盘点单列表
        Intent intent = new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300089.IndexActivity.class);
        IndexActivity.this.startActivity(intent);
    }

    /**
     * 扫描 接收者
     *
     * @author: zhongfan
     * @Date 2022/2/15 21:00
     **/
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String msg = intent.getStringExtra(BusinessConstants.TAG);

            if (assetIdList.indexOf(msg) != -1) {
                Toast.makeText(IndexActivity.this, "请不要重复扫描", Toast.LENGTH_SHORT).show();
                return;
            }

            Log.i(BusinessConstants.TAG, msg);
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("facardcode", msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            queryAssets(jsonObject);
        }

    };

    /**
     * 查询资产
     */
    private void queryAssets(JSONObject jsonObject) {
        Log.v("dataMap2:", dataMap.toString());
        service.post(jsonObject, HttpUrlComstants.QUERY_ASSET_DETAILS, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {

                    JSONObject jsonObject3 = JsonUtil.getJsonObject(response, "facardinfo", IndexActivity.this);
                    if (jsonObject3 == null) {
                        Toast.makeText(IndexActivity.this, "查询信息为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    Map<String, Object> dataMam = new HashMap<>();
                    //位置名称
                    String locationName = jsonObject3.getString("location");
                    dataMam.put(BusinessConstants.LOCATION_NAME, StringUtils.isEmpty(locationName) ? "" : locationName);
                    //使用人
                    String usedPsnCode = jsonObject3.getString("usedpsncode");
                    String usedPsnName = jsonObject3.getString("usedpsnname");
                    dataMam.put(BusinessConstants.USED_PSN, StringUtils.isEmpty(usedPsnCode) ? "" : usedPsnCode + "-" + usedPsnName);
                    Object computerName = jsonObject3.get(BusinessConstants.COMPUTER_NAME);
                    dataMam.put(BusinessConstants.COMPUTER_NAME, StringUtils.isEmpty(computerName.toString()) ? "" : computerName);
                    Object facardcode = jsonObject3.get("facardcode");
                    dataMam.put(BusinessConstants.CARD_NUMBER, StringUtils.isEmpty(facardcode.toString()) ? "" : facardcode);
                    Object physicalcode = jsonObject3.get("physicalcode");
                    dataMam.put(BusinessConstants.PHYSICAL_CODE, StringUtils.isEmpty(physicalcode.toString()) ? "" : physicalcode);
                    Object maname = jsonObject3.get("maname");
                    dataMam.put(BusinessConstants.MA_NAME, StringUtils.isEmpty(maname.toString()) ? "" : maname);
                    Object manumber = jsonObject3.get("manumber");
                    dataMam.put(BusinessConstants.MA_NUMBER, StringUtils.isEmpty(manumber.toString()) ? "" : manumber);
                    Object facardid = jsonObject3.get("facardid");
                    dataMam.put(BusinessConstants.CARD_ID, StringUtils.isEmpty(facardid.toString()) ? "" : facardid);
                    Object num = jsonObject3.get("num");
                    dataMam.put(BusinessConstants.CARD_NUM, StringUtils.isEmpty(num.toString()) ? "" : num);

                    if (assetIdList.indexOf(dataMam.get("facardcode")) == -1) {
                        //后面扫描的显示在最前面
                        /*List<Map<String, Object>> map=new ArrayList<>();
                        map.add(dataMam);
                        map.addAll(dataMap);
                        dataMap=map;*/
                        dataMap.add(dataMam);
                    }

                    assetIdList.add(jsonObject3.optString("facardcode"));

                    //盘点背景设置为空
                    recyclerView.setBackground(null);

                    //通知ListView更改数据源
                    if (recyclerViewAdapter != null) {
                        recyclerViewAdapter.notifyDataSetChanged();
                    } else {
                        recyclerViewAdapter = new RecyclerViewAdapter(dataMap);
                        recyclerView.setAdapter(recyclerViewAdapter);
                    }
                    recyclerView.setSelected(true);
                  //设置显示列表的最后一项 dataMap.size() - 1
                    int lastPosition = dataMap.size() - 1;    // 获取最后一项的位置
                    if (lastPosition >= 0) {   // 如果列表项大于0，滚动到最后一项
                        recyclerView.scrollToPosition(lastPosition);
                    }
                    saveInfo(dataMam.get(BusinessConstants.CARD_ID));
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtils.makeText(IndexActivity.this, e.getMessage(), ToastUtils.LENGTH_SHORT).show();
                }
            }

        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 保存盘点信息
     */
    public void saveInfo(Object cardId) {
        JSONObject inObject = new JSONObject();
        try {
            if (StringUtils.isEmpty(data.getString(BusinessConstants.ID))) {
                Log.e("error", "盘点计划id不能为空");
                return;
            }
            //盘点计划id
            inObject.put(BusinessConstants.INVENTORY_PLANIID, data.getString(BusinessConstants.ID));
            //资产id
            inObject.put(BusinessConstants.CARD_ID, cardId);
            //实盘数量:一物一码
            inObject.put(BusinessConstants.INVENTORY_NUM, 1);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        service.post(inObject, HttpUrlComstants.ASSETS_SAVE_DETAIL, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Toast.makeText(IndexActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
            }
        });
    }

    /**
     * 通过盘点计划id查询已盘点资产信息
     *
     * @return void
     * @author: 黄斌成
     * @Date 2022/12/13 17:11
     **/
    public void queryCountAssets() {
        if (StringUtils.isEmpty(inventoryPlanId)) {
            Toast.makeText(IndexActivity.this, "盘点计划id为空", Toast.LENGTH_SHORT).show();
        }
        Map<String, Object> inMap = new HashMap<>();
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("pageIndex", 1);
        pageMap.put("pageSize", 9999999);
        inMap.put("page", pageMap);
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(BusinessConstants.INVENTORY_PLANIID, inventoryPlanId);
        queryMap.put(BusinessConstants.SCAN_RESULT_CODE, scanResultCode);
        inMap.put("query", queryMap);

        service.post(JsonUtil.toJSONObject(inMap), HttpUrlComstants.FA_CARD_INVENTORY_DETAIL, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {
                    JSONArray result = JsonUtil.toJsonObjectArray(response, "content", IndexActivity.this);
                    if (result == null || result.length() == 0) {
                        Toast.makeText(IndexActivity.this, "获取数据为空", Toast.LENGTH_SHORT).show();
                        recyclerView.setBackgroundResource(R.drawable.toolbar_bg_selector);
                        return;
                    }

                    initialAssetsNum = result.length();
                    for (int i = 0; i < result.length(); i++) {
                        Map<String, Object> map = new HashMap<>(3);
                        map.put(BusinessConstants.ID, result.getJSONObject(i).get(BusinessConstants.ID));
                        //实物码
                        Object cardNumber = result.getJSONObject(i).get(BusinessConstants.CARD_NUMBER);
                        map.put(BusinessConstants.CARD_NUMBER, StringUtils.isEmpty(cardNumber.toString()) ? "" : cardNumber);
                        //位置名称
                        String locationName = result.getJSONObject(i).getString(BusinessConstants.LOCATION_NAME);
                        map.put(BusinessConstants.LOCATION_NAME, StringUtils.isEmpty(locationName) ? "" : locationName);
                        //使用人
                        String usedPsnCode = result.getJSONObject(i).getString("usedPsnCode");
                        String usedPsnName = result.getJSONObject(i).getString("usedPsnName");
                        map.put(BusinessConstants.USED_PSN, StringUtils.isEmpty(usedPsnCode) ? "" : usedPsnCode + "-" + usedPsnName);
                        //资产编码
                        Object physicalCode = result.getJSONObject(i).get(BusinessConstants.PHYSICAL_CODE);
                        map.put(BusinessConstants.PHYSICAL_CODE, StringUtils.isEmpty(physicalCode.toString()) ? "" : physicalCode);
                        //计算机名
                        Object computerName = result.getJSONObject(i).get(BusinessConstants.COMPUTER_NAME);
                        map.put(BusinessConstants.COMPUTER_NAME, StringUtils.isEmpty(computerName.toString()) ? "" : computerName);
                        //台账数量
                        Object cardNum = result.getJSONObject(i).get(BusinessConstants.CARD_NUM);
                        map.put(BusinessConstants.CARD_NUM, StringUtils.isEmpty(cardNum.toString()) ? "" : cardNum);
                        //实盘数量
                        Object inventoryNum = result.getJSONObject(i).get(BusinessConstants.INVENTORY_NUM);
                        map.put(BusinessConstants.INVENTORY_NUM, StringUtils.isEmpty(inventoryNum.toString()) ? "" : inventoryNum);
                        //物料编号
                        Object maNumber = result.getJSONObject(i).get(BusinessConstants.MA_NUMBER);
                        map.put(BusinessConstants.MA_NUMBER, StringUtils.isEmpty(maNumber.toString()) ? "" : maNumber);
                        //物料名称
                        Object maName = result.getJSONObject(i).get(BusinessConstants.MA_NAME);
                        map.put(BusinessConstants.MA_NAME, StringUtils.isEmpty(maName.toString()) ? "" : maName);
                        //异常原因备注
                        Object exceptionMemo = result.getJSONObject(i).get(BusinessConstants.EXCEPTION_MEMO);
                        map.put(BusinessConstants.EXCEPTION_MEMO, StringUtils.isEmpty(exceptionMemo.toString()) ? "" : exceptionMemo);

                        dataMap.add(map);
                        assetIdList.add(result.getJSONObject(i).get(BusinessConstants.CARD_NUMBER).toString());
                    }
                    //通知ListView更改数据源
                    if (recyclerViewAdapter != null) {
                        recyclerViewAdapter.notifyDataSetChanged();
                    } else {
                        recyclerViewAdapter = new RecyclerViewAdapter(dataMap);
                        recyclerView.setAdapter(recyclerViewAdapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
            }
        });
    }

    /**
     * 根据盘点类型 删除按钮
     *
     * @param inventoryStatus
     * @return void
     * @author: zhongfan
     * @Date 2022/2/21 17:52
     **/
    public void deleteButton(String inventoryStatus) {
        if ("1".equals(inventoryStatus)) {
            llButton.removeView(btInventoryCompleted);
        } else if ("2".equals(inventoryStatus) || "3".equals(inventoryStatus)) {
            llButton.removeView(btReceiver);
            //llButton.removeView(btSave);
        } else {
            llButton.removeView(btReceiver);
            //llButton.removeView(btSave);
            llButton.removeView(btInventoryCompleted);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.go_back:
                intent = new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300089.IndexActivity.class);
                IndexActivity.this.startActivity(intent);
                break;
            case R.id.bt_inventory_completed:
                intent = new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300028.IndexActivity.class);
                intent.putExtra(BusinessConstants.DATA, data.toString());
                // 使用activtiy的startActivityForResult方法跳转，第二参数是请求码，第二方数据回传时我们通过requestCode来判断是哪个页面
                IndexActivity.this.startActivityForResult(intent, BusinessConstants.requestCode);
                break;
        }
    }

    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (ActivityUtil.isShouldHideKeyboard(v, ev)) {
                ActivityUtil.hideKeyboard(v.getWindowToken(), this, etAssets);
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 11) {
            dataMap.clear();
            assetIdList.clear();
            //刷新列表
            queryCountAssets();
        }

    }

}
